package com.henry.imkit.network

import com.henry.imkit.ErrorCode
import com.henry.imkit.utils.IMLogErr
import org.bson.json.JsonParseException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException

class IMExceptionHandle {

    companion object {
        var errorCode = ErrorCode.UNKNOWN_ERROR
        var errorMsg = "请求失败，请稍后重试"

        fun handleException(e: Throwable): String {
            e.printStackTrace()
            if (e is SocketTimeoutException
                    || e is ConnectException
                    || e is HttpException
            ) { //均视为网络错误
                IMLogErr("网络连接异常: " + e.message)
                errorMsg = "网络连接异常"
                errorCode = ErrorCode.NETWORK_ERROR
            } else if (e is JsonParseException
                    || e is JSONException
                    || e is ParseException
            ) {   //均视为解析错误
                IMLogErr("数据解析异常: " + e.message)
                errorMsg = "数据解析异常"
                errorCode = ErrorCode.SERVER_ERROR
            } else if (e is ApiException) {//服务器返回的错误信息
                errorMsg = e.message.toString()
                errorCode = ErrorCode.SERVER_ERROR
            } else if (e is UnknownHostException) {
                IMLogErr("网络连接异常: " + e.message)
                errorMsg = "网络连接异常"
                errorCode = ErrorCode.NETWORK_ERROR
            } else if (e is IllegalArgumentException) {
                errorMsg = "参数错误"
                errorCode = ErrorCode.SERVER_ERROR
            } else {//未知错误
                try {
                    IMLogErr("错误: " + e.message)
                } catch (e1: Exception) {
                    IMLogErr("未知错误Debug调试 ")
                }
//                errorMsg = "未知错误，可能抛锚了吧~"
//                errorCode = ErrorStatus.UNKNOWN_ERROR
                // TODO 过期，重新登录
                // <script type="text/javascript">if(parent && parent.location && parent.location.href) {parent.location.href='/RTIS/login.ered?reqCode=init';}else{window.location.href='/RTIS/login.ered?reqCode=init';}</script>
                errorMsg = "已过期，请重新登录"
                errorCode = ErrorCode.TOKEN_INVALID

            }
            return errorMsg
        }

    }

}